package o2o.web.actions.base;

import com.jinyou.utils.common.*;
import o2o.cache.sys.SysConfigVerifyMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.sys.SysConfigPath;
import o2o.dao.PO.sys.SysConfigVerify;
import o2o.dao.PO.sys.SysCustomerInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.sys.SysConfigPathVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

// 系统目录配置base查询

@Controller
public class SysConfigPathAction {
    //列表
    @RequestMapping(method = RequestMethod.POST, value = "/base/sys-config-path/list")
    @ResponseBody
    public String category_list(String apiKey, String sysAppKey, String params) {
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        QueryCondition query = QueryCondition.getInstance();

        query.addCondition(Expression.getInstance().addChild("delFlag", 0));
        String sql = DaoUtils.getSql(PojoTables.SYS_CONFIG_PATH, query);
        List<SysConfigPath> list = null;
        try {
            list = (List<SysConfigPath>) UserDaoSql.getInstance().list(SysConfigPath.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (ValidateUtil.isAbsList(list)) {
            List<SysConfigPathVO> voList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                SysConfigPathVO vo = new SysConfigPathVO();
                try {
                    ObjectUtils.copyPropertiesExclude(list.get(i), vo, null);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (params != null && params != "") {
                    if (list.get(i).getCode().contains(params)) {
                        voList.add(vo);
                    }
                } else {
                    voList.add(vo);
                }
            }
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        }

        return AjaxResult.successResult(0, null);
    }
    //列表
    @RequestMapping(method = RequestMethod.POST, value = "/base/sys-config-verify/list")
    @ResponseBody
    public String config_verify_list(String apiKey, String sysAppKey) {
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        QueryCondition query = QueryCondition.getInstance();

        query.addCondition(Expression.getInstance().addChild("delFlag", 0).addChild("isAliLogin", 0));
        String sql = DaoUtils.getSql(PojoTables.SYS_CONFIG_VERIFY, query);
        List<SysConfigVerify> list = null;
        try {
            list = (List<SysConfigVerify>) UserDaoSql.getInstance().list(SysConfigVerify.class, sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return AjaxResult.successResult(list);
    }

    //列表(查询阿里云一键登录相关配置)
    @RequestMapping(method = RequestMethod.POST, value = "/base/sys-config-verify-aliLogin/list")
    @ResponseBody
    public String config_verify_aliLogin_list(String apiKey, String sysAppKey) {
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }
            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        QueryCondition query = QueryCondition.getInstance();

        query.addCondition(Expression.getInstance().addChild("delFlag", 0).addChild("isAliLogin", 1));
        String sql = DaoUtils.getSql(PojoTables.SYS_CONFIG_VERIFY, query);
        List<SysConfigVerify> list = null;
        try {
            list = (List<SysConfigVerify>) UserDaoSql.getInstance().list(SysConfigVerify.class, sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return AjaxResult.successResult(list);
    }

    // 用户端获取(查询阿里云一键登录相关配置)信息
    @RequestMapping(method = RequestMethod.POST, value = "/user/sysConfigVerifyAliLogin/info")
    @ResponseBody
    public String userSysConfigVerifyAliLoginInfo() {
        SysConfigVerify aliLogin = SysConfigVerifyMemory.getInstance().getAliLogin(null);
        if (aliLogin != null) {
            return AjaxResult.successResult(aliLogin);
        }
        return AjaxResult.successResult();
    }

    //  添加
    @RequestMapping(method = RequestMethod.POST, value = "/base/sys-config-verify/modify")
    @ResponseBody
    public String modify(String apiKey, SysConfigVerify info) {
        if (null == info) {
            return AjaxResult.errorResult("请补全信息");
        }
        try {
//            SysSettingDB pc = new SysSettingDB();
//            ObjectUtils.copyPropertiesExclude(info, pc, null);
            if (ValidateUtil.isNotID(info.getId())) {
                UserDaoSql.getInstance().insertObj(PojoTables.SYS_CONFIG_VERIFY, info);
            } else {
                StringBuilder sb = new StringBuilder();
                String aliVerifyType = "";
                if (StringUtils.isNotEmpty(info.getAliVerifyType())) {
                    aliVerifyType = " aliVerifyType='" + info.getAliVerifyType() + "',";
                } else {
                    aliVerifyType = " aliVerifyType='',";
                }
                String aliVerifyBiz = "";
                if (StringUtils.isNotEmpty(info.getAliVerifyBiz())) {
                    aliVerifyBiz = " aliVerifyBiz='" + info.getAliVerifyBiz() + "',";
                } else {
                    aliVerifyBiz = " aliVerifyBiz='',";
                }
                String sysAppKey = "";
                if (StringUtils.isNotEmpty(info.getSysAppKey())) {
                    sysAppKey = " sysAppKey='" + info.getSysAppKey() + "',";
                }
                String isAble = "";
                if (null != info.getIsAble()) {
                    isAble = " isAble=" + info.getIsAble() + ",";
                }
                String aliEndpoint = "";
                if (null != info.getAliEndpoint()) {
                    aliEndpoint = " aliEndpoint='" + info.getAliEndpoint() + "',";
                }
                String androidSdkKey = "";
                if (null != info.getAndroidSdkKey()) {
                    androidSdkKey = " androidSdkKey='" + info.getAndroidSdkKey() + "',";
                }
                String iosSdkKey = "";
                if (null != info.getIosSdkKey()) {
                    iosSdkKey = " iosSdkKey='" + info.getIosSdkKey() + "',";
                }
                sb.append("update ").append(PojoTables.SYS_CONFIG_VERIFY)
                        .append(" set aliAccessKeyId='").append(info.getAliAccessKeyId()).append("',")
                        .append(aliVerifyType).append(aliVerifyBiz).append(sysAppKey).append(isAble)
                        .append(aliEndpoint).append(androidSdkKey).append(iosSdkKey)
                        .append(" aliAccessKeySecret='").append(info.getAliAccessKeySecret()).append("'")
                .append(" where id = ").append(info.getId());
                UserDaoSql.getInstance().executeBySql(sb.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("保存失败，请稍后再试");
        }
        o2o.system.SysConfigPath.init();//重新初始化系统值
        return AjaxResult.successResult();
    }
    //  添加
    @RequestMapping(method = RequestMethod.POST, value = "/base/sys-config-path/add")
    @ResponseBody
    public String add(String token, String apiKey, String sysAppKey, SysConfigPath info) {
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }

            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if (null == info) {
            return AjaxResult.errorResult("请补全信息");
        }
        if (ValidateUtil.isNull(info.getCode())) {
            return AjaxResult.errorResult("标识不能为空");
        }
        try {
//            SysSettingDB pc = new SysSettingDB();
//            ObjectUtils.copyPropertiesExclude(info, pc, null);
            info.setCreateUser("base");
            info.setCreateTime(DateUtils.getCurrTime());
            UserDaoSql.getInstance().insertObj(PojoTables.SYS_CONFIG_PATH, info);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("新增失败，请稍后再试");
        }
        o2o.system.SysConfigPath.init();//重新初始化系统值
        return AjaxResult.successResult();
    }

    //  修改
    @RequestMapping(method = RequestMethod.POST, value = "/base/sys-config-path/modify")
    @ResponseBody
    public String modify(String token, String apiKey, String sysAppKey, SysConfigPath info) {
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }

            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if (null == info) {
            return AjaxResult.errorResult("请补全信息");
        }
        if (ValidateUtil.isNull(info.getCode())) {
            return AjaxResult.errorResult("标识不能为空");
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.SYS_CONFIG_PATH)
                .append(" set path='").append(info.getPath())
                .append("',note='").append(info.getNote())
                .append("',code='").append(info.getCode())
                .append("',updateUser='").append("base")
                .append("' where  id = '").append(info.getId()).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //修改缓存
        o2o.system.SysConfigPath.init();//重新初始化系统值
        return AjaxResult.successResult();
    }
    //  删除
    @RequestMapping(method = RequestMethod.POST, value = "/base/sys-config-path/delete")
    @ResponseBody
    public String delete(String token, String apiKey, String sysAppKey, SysConfigPath info) {
        UserInfo user = new UserInfo();
        try {
            String decrypt = EncrypAES.aesDecrypt(apiKey, "abcdefgabcdeg12p");
            if (ValidateUtil.isNull(sysAppKey)) {
                sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
            }

            SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
            if (null != customerInfo) {
                if (!decrypt.equals(customerInfo.getApiKey())) {
                    return AjaxResult.errorResult("您没有访问权限");
                }
            } else {
                return AjaxResult.errorResult("没有客户信息");
            }
            user.setUsername("base");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.SYS_CONFIG_PATH)
                .append(" set delFlag='").append(info.getDelFlag())
                .append("',updateUser='").append(user.getUsername())
                .append("' where  id = '").append(info.getId()).append("'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除失败，请稍后再试");
        }

        //修改缓存
        o2o.system.SysConfigPath.init();//重新初始化系统值
        return AjaxResult.successResult();
    }
}
